package revontuli.aMHD.datamanagement;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import revontuli.aMHD.aMHDApp;

import android.util.Log;

public class HTTPRetriever {
	private DefaultHttpClient mClient = new DefaultHttpClient();
	
	public String retrieve(String url) {
		HttpGet getRequest = new HttpGet(url);
		
		try {
			HttpResponse getResponse = mClient.execute(getRequest);
			final int mStatus = getResponse.getStatusLine().getStatusCode();
			
			if (mStatus != HttpStatus.SC_OK) {
				Log.w(aMHDApp.TAG, "Error " + mStatus + "when retrieving URL " + url);
				return null;
			}
			
			HttpEntity getResponseEntity = getResponse.getEntity();
			
			if (getResponseEntity != null) {
				return EntityUtils.toString(getResponseEntity, HTTP.UTF_8);
			}
			
		} catch (IOException e) {
			getRequest.abort();
			Log.w(aMHDApp.TAG, "Error when retrieving URL " + url, e);
		}
		
		return null;
		
	}
	
	public InputStream retrieveStream(String url) {
		HttpGet getRequest = new HttpGet(url);
		
		try {
			HttpResponse getResponse = mClient.execute(getRequest);
			final int mStatus = getResponse.getStatusLine().getStatusCode();
			
			if (mStatus != HttpStatus.SC_OK) {
				Log.w(aMHDApp.TAG, "Error " + mStatus + "when retrieving URL " + url);
				return null;
			}
			
			HttpEntity getResponseEntity = getResponse.getEntity();
			
			return getResponseEntity.getContent();
			
		} catch (IOException e) {
			getRequest.abort();
			Log.w(aMHDApp.TAG, "Error when retrieving URL " + url, e);
		}
		
		return null;
	}
	
	public static void closeStream(InputStream input) {
		try {
			if (input != null) {
				input.close();
			}
		} catch (IOException e) {
		}
	}
	
}
